<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="keyword"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
      @search="onSearch(keyword)"
    >
      <template #action>
        <div @click="onSearch(keyword)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group v-if="keyword">
      <van-cell
        icon="search"
        v-for="item in searchList"
        :key="item"
        @click="onSearch(item)"
      >
        <span v-html="highLight(item, keyword)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell :title="item" v-for="item in historyList" :key="item">
        <van-icon name="close" @click="del(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import { setStoregeHistory, getStoreHistory } from '@/utils/store'
export default {
  name: 'Search',
  data() {
    return {
      keyword: '',
      searchList: [],
      historyList: getStoreHistory()
    }
  },
  methods: {
    onSearch(keyword) {
      if (!keyword) {
        return this.$toast('请输入关键字')
      }
      this.historyList = this.historyList.filter(v => v !== keyword)
      this.historyList.unshift(keyword)
      setStoregeHistory(this.historyList)
      // 跳转传参
      this.$router.push({
        path: '/search/result',
        query: {
          keyword
        }
      })
    },
    del(keyword) {
      this.historyList = this.historyList.filter(v => v !== keyword)
      setStoregeHistory(this.historyList)
    },
    inputFn() {
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        if (this.keyword === '') {
          return
        }
        const res = await getSuggest(this.keyword)
        console.log('搜索结果', res)
        this.searchList = res.data.options
      }, 300)
    },
    // 高亮
    highLight(str, keyword) {
      return str.replace(
        new RegExp(keyword, 'gi'),
        item => `<span style="color: red">${item}</span>`
      )
    }
  }
}
</script>

<style></style>
